package org.madgecko.basic.service.impl;

import org.madgecko.basic.model.Pager;
import org.madgecko.basic.util.SecurityUtil;
import org.madgecko.basic.dao.iface.IClazzDao;
import org.madgecko.basic.dao.iface.IStudentDao;
import org.madgecko.basic.dao.iface.IUserDao;
import org.madgecko.basic.model.Clazz;
import org.madgecko.basic.model.Student;
import org.madgecko.basic.model.exception.TRException;
import org.madgecko.basic.service.iface.IStudentService;
import org.madgecko.common.util.FileTool;
import org.madgecko.common.util.XlsTools;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.security.NoSuchAlgorithmException;
import java.util.Collection;
import java.util.Date;
import java.util.List;

@Service
public class StudentService implements IStudentService {

	@Inject
	private IStudentDao studentDao;
	@Inject
	private IClazzDao clazzDao;
	@Inject
	private IUserDao userDao;

	@Override
	public void add(Student student) {
		studentDao.add(student);
	}

	@Override
	public void delete(Integer id) {
		studentDao.delete(id);
	}

	@Override
	public void update(Student student) {
		studentDao.update(student);
	}

	@Override
	public Student load(Integer id) {
		return studentDao.load(id);
	}

	@Override
	public Student loadByStuNum(String stuNum) {
		return studentDao.loadByStuNum(stuNum);
	}

	@Override
	public Pager<Student> findStudentByCon(Integer status, Integer clazzId, String con) {
		return studentDao.findStudentByCon(status, clazzId, con);
	}

	@Override
	public List<Student> listStudentByClazz(Integer clazzId) {
		return studentDao.listStudentByClazz(clazzId);
	}

	@Override
	public boolean importIn(MultipartFile file, Integer clazzId, HttpServletRequest req, HttpSession session) {
		Clazz c = clazzDao.load(clazzId);
		if(null==c){
			throw new TRException("班级不存在.");
		}

		String fullStorePath = FileTool.saveTempFile(file, req);
		File importFile = new File(fullStorePath);
		//此处Student的stuNum为String类型,所以excel里的学号也应该为文本类型
		Collection col = XlsTools.importExcel(importFile, Student.class, "");
		try {
			for(Object o : col){
				Student s = (Student)o;
				s.setClazz(c);
				s.setClazzName(c.getName());
				s.setCreateDate(new Date());
				s.setStatus(1);
				s.setPassword(SecurityUtil.md5("123456"));
				this.add(s);
			}
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			return false;
		}
		importFile.deleteOnExit();
		return true;
	}
}
